<?php

namespace app\common\model;
use think\Db;
use think\Model;

class StReservation extends Model
{
    protected $pk = 'id';
    protected  $name = "st_reservation";
    protected $autoWriteTimestamp = true;// 自动写入时间戳
    protected $hidden=['comid','create_time','uid'];

    public function StReservationAttr()
    {
        return $this->hasMany(StReservationAttr::class,'mid' ,'id');
    }
    //新增
    public function addStReservation($data){
        Db::startTrans();
        try {
            foreach ($data as $val){
                $re =  self::create($val);
                $re->StReservationAttr()->saveAll($re['sub_data']);
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
           return $e->getMessage();
        }
        return true;
    }

    //获取列表
    public function getReservaList($map){
        $list = self::where($map)->order('date','desc')->paginate();
        foreach ($list as $key=>$value){
            $value->StReservationAttr;

            $list[$key]['reservation_attr'] = "";
            foreach ($value['StReservationAttr'] as $k=>$vo){
                if ($vo['attr_status']==0) $attrStatus='【<font color="#ff7f50">待用餐</font>】;';
                if ($vo['attr_status']==1) $attrStatus='【<font color="#00bfff">已用餐</font>】;';
                if ($vo['attr_status']==2) $attrStatus='【<font color="red">已取消</font>】;';
                $list[$key]['reservation_attr'] .= $vo['attr_name'].$attrStatus;

            }
        }

        return $list;
    }



    public static function ApiGetReservaByDate($uid){
        $date       = date('Y-m-d',time());
        $time       = date('H:i:s',time());
        $map = [
            ['a.uid', '=', $uid],
            ['a.status','=', 1],
            ['a.date', '=', $date],
            ['b.start_time', '<=', $time],
            //['b.end_time', '>=', $time],
            //['b.attr_status', '=', 0],
        ];
        $row = self::where($map)->alias('a')
            ->leftJoin("st_reservation_attr b", 'a.id = b.mid')
            ->order(['b.start_time'=>'desc'])
            ->field('a.user_name,a.date , b.*')
            ->find();
        return $row;
    }

}